package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.common.BaseServiceImpl;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionServiceImpl extends BaseServiceImpl<ApCollectionMapper, ApCollection>{
    @Autowired
    private BehaviorFeign behaviorFeign;


    public ResponseResult collection(CollectionBehaviorDto dto) {
        //1.判断传递过来的参数是否为空
        if (dto == null ||  dto.getArticleId() == null || dto.getType() < 0 || dto.getType() > 1 || dto.getOperation() <0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getEquipmentId()==null){
            dto.setEquipmentId(0);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        //2.查询行为实体
        ApBehaviorEntry entry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(),dto.getEquipmentId());
        //3.查询表中是否存在收藏的数据
        ApCollection one =(ApCollection) getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getArticleId()).eq(ApCollection::getEntryId, entry.getId()));

        //如果行为不存在，往表中保存数据
        if (one == null){
            //判断是否是收藏行为
            if (dto.getOperation() == 0){
                ApCollection collection = new ApCollection();
                collection.setArticleId(dto.getArticleId());
                collection.setEntryId(entry.getId());
                collection.setCollectionTime(new Date());
                collection.setType(dto.getType());
                save(collection);
            }else {
                //删除表中的收藏数据
                removeById(dto.getArticleId());
                return ResponseResult.okResult("取消收藏");
            }
        }else {
            return ResponseResult.okResult("文章已经收藏！！");
        }
        return null;
    }
}
